//
//  OpenAPIServices.m
//  doubleEduStudents
//
//  Created by 盛洋 on 2021/2/18.
//  Copyright © 2021 shengYang. All rights reserved.
//

#import "OpenAPIServices.h"
static OpenAPIServices *_openAPIService = nil;

@implementation OpenAPIServices

+ (OpenAPIServices*)sharedService{
    @synchronized(self){
        if(!_openAPIService){
            _openAPIService = [[OpenAPIServices alloc] init];
        }
    }
    return _openAPIService;
}

#pragma mark -重写 AppDelegate 的 handleOpenURL 和 openURL 方法
- (BOOL)handleOpenURL:(NSURL *)url sourceApplication:sourceApplication annotation:annotation{
    if (url) {
        NSString* path =[[url absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        NSLog(@"url路径--%@",path);
        NSRange range = [path rangeOfString:@"tencent"];//判断字符串是否包含
        if (range.length >0){ //包含
            NSRange range = [path rangeOfString:@"error=0"];
            NSRange range1 = [path rangeOfString:@"result=complete"];
            if (range.length>0 || range1.length>0) {
                
            }
        }
    }
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)handleOpenURL:(NSURL *)url {
    if (url) {
        NSString* path =[[url absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        NSLog(@"url路径--%@",path);
        NSRange range = [path rangeOfString:@"tencent"];//判断字符串是否包含
        if (range.length >0){ //包含
            NSRange range = [path rangeOfString:@"error=0"];
            NSRange range1 = [path rangeOfString:@"result=complete"];
            //NSLog(@"1111");
            if (range.length>0 || range1.length>0) {
                
            }
        }
    }
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (result == NO) {
        //调用其他SDK，例如新浪微博SDK等
    }
    return result;
}


#pragma mark -友盟分享
- (void)setUmengAppKey{
    
    //配置微信平台的Universal Links
    //微信和QQ完整版会校验合法的universalLink，不设置会在初始化平台失败
    [UMSocialGlobal shareInstance].universalLinkDic = @{@(UMSocialPlatformType_WechatSession):@"https://developer.umeng.com/",@(UMSocialPlatformType_QQ):@"https://developer.umeng.com/"};
    
    [UMConfigure initWithAppkey:UMKEY channel:@"App Store"];
    /*
     设置微信的appKey和appSecret
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:APPKEY_WEIXIN appSecret:APPSecret_WEIXIN redirectURL:@"http://mobile.umeng.com/social"];
    
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:APPID_QQ/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
    
    /*
     设置新浪的appKey和appSecret
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:APPKEY_SINA appSecret:APPSecret_SINA redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
}

// 根据平台名，返回平台对象
- (void)setPlatformSSO:(UIViewController*)controller platformName:(UMSocialPlatformType)snsName {
    
    //[[NSNotificationCenter defaultCenter] postNotificationName:@"ShowMBProgressHUD" object:nil];
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:snsName currentViewController:controller completion:^(id result, NSError *error) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ShowMBProgressHUD" object:nil];
        UMSocialUserInfoResponse *resp = result;
        
        NSString *message = nil;
        
        if (error) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HideMBProgressHUD" object:nil];
            if(_delegate && [_delegate respondsToSelector:@selector(openFailed:)]){
                [_delegate openFailed:resp];
            }
        }
        else{
            if ([result isKindOfClass:[UMSocialUserInfoResponse class]]) {
                
                UMSocialUserInfoResponse *resp = result;
                if(_delegate && [_delegate respondsToSelector:@selector(openLoginSucce:snsName:)]){
                    [_delegate openLoginSucce:resp snsName:snsName];
                }
            }
            else{
                message = @"Get info fail";
            }
        }
    }];
}

//友盟分享的数据
- (void)shareInfo: (UIViewController*)controller urlString:(NSString*)_stringURL titleString:(NSString *)_titleString titleImage:(UIImage *)image desc:(NSString*)desc infoID:(NSString*)infoID
{
    shareInfoID = infoID;
    
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_QQ),@(UMSocialPlatformType_Qzone),@(UMSocialPlatformType_Sina)]];
    
//    [UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_UserDefine_Begin+2
//                                     withPlatformIcon:[UIImage imageNamed:@"weixin"]
//                                     withPlatformName:@"复制链接"];
    
    [UMSocialShareUIConfig shareInstance].sharePageGroupViewConfig.sharePageGroupViewPostionType = UMSocialSharePageGroupViewPositionType_Bottom;
    [UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageItemStyleType = UMSocialPlatformItemViewBackgroudType_None;
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        
        if (platformType == UMSocialPlatformType_UserDefine_Begin+2) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = _stringURL;
                cnhbMsgAlert *alert = [[cnhbMsgAlert alloc] init];
                [alert setTextColor:[UIColor whiteColor]];
                [alert showMessage:@"复制到剪贴板"];
                
            });
        }
        else {
            //创建分享消息对象
            UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            
            if (platformType == UMSocialPlatformType_Sms)
            {
                UMShareSmsObject *shareObjectSms = [[UMShareSmsObject alloc]init];
                shareObjectSms.smsContent = [NSString stringWithFormat:@"%@\n%@\n来自于阿列夫星球，与您分享",_titleString,_stringURL];
                messageObject.shareObject = shareObjectSms;
            }
            else if (platformType == UMSocialPlatformType_Sina) {
                
                messageObject.text = [NSString stringWithFormat:@"%@%@",_titleString,_stringURL];
                
                //创建图片内容对象
                UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
                if (image) {
                    
                    shareObject.thumbImage = image;
                    shareObject.shareImage = image;
                    
                    messageObject.shareObject = shareObject;
                }
                else {
                    shareObject.thumbImage = [UIImage imageNamed:@"AppIcon60x60@3x.png"];
                    shareObject.shareImage = [UIImage imageNamed:@"AppIcon60x60@3x.png"];
                }
            }
            else
            {
                UMShareWebpageObject *shareObject;
                if (!image) {
                    shareObject = [UMShareWebpageObject shareObjectWithTitle:_titleString descr:desc thumImage:[UIImage imageNamed:@"AppIcon60x60@3x.png"]];
                }
                else {
                    shareObject = [UMShareWebpageObject shareObjectWithTitle:_titleString descr:desc thumImage:image];
                }
                shareObject.webpageUrl = _stringURL;
                
                messageObject.shareObject = shareObject;
            }
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:controller completion:^(id data, NSError *error) {
                
                if (error) {
                    UMSocialLogInfo(@"************Share fail with error %@*********",error);
                }else{
                    if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                        UMSocialShareResponse *resp = data;
                        //分享结果消息
                        UMSocialLogInfo(@"response message is %@",resp.message);
                       // 第三方原始返回的数据
                        UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                        [self backCall];
                    }else{
                        UMSocialLogInfo(@"response data is %@",data);
                    }
                }
                [self alertWithError:error];
            }];
        }
    }];
}

- (void)alertWithError:(NSError *)error
{
    NSString *result = nil;
    if (!error) {
        result = [NSString stringWithFormat:@"Share succeed"];
    }
    else{
        NSMutableString *str = [NSMutableString string];
        if (error.userInfo) {
            for (NSString *key in error.userInfo) {
                [str appendFormat:@"%@ = %@\n", key, error.userInfo[key]];
            }
        }
        if (error) {
            result = [NSString stringWithFormat:@"Share fail with error code: %d\n%@",(int)error.code, str];
        }
        else{
            result = [NSString stringWithFormat:@"Share fail"];
        }
    }
    NSLog(@"分享结果--%@--",result);
}


//分享回调
- (void)backCall{
    if (shareInfoID != nil && ![shareInfoID isEqualToString:@""]) {
//        RequestServices *rs = [[RequestServices alloc] initWithDelegate:self];
//        [rs postClickNewsCallback:shareInfoID option:1 tag:12];
    }
}

@end
